package com.gexin.common.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import com.jfinal.kit.LogKit;

public class ImgDownload {

	/**
	 * 文件临时存储的目录
	 */
	public final static String File_Temp_Path = System.getProperty("java.io.tmpdir") + DateUtil.getDate("yyyyMMdd") + File.separator;

	static {
		File f = new File(File_Temp_Path);
		if (!f.exists()) {
			f.mkdir();
		}
	}

	public static void main(String[] args) throws Exception {
		System.err.println(File_Temp_Path);
		System.err.println(File.separator);
		String url = "http://img.shandian001.com/tumblr_o7h9y4iBXV1ua18yao1_500.jpg";
		String[] sp = url.split("/");
		System.err.println(sp[sp.length - 1]);
		download("http://img.shandian001.com/tumblr_o7h9y4iBXV1ua18yao1_500.jpg");
	}

	/**
	 * 下载文件到本地
	 *
	 * @param urlString 被下载的文件地址
	 * @param filename  本地文件名
	 * @throws Exception 各种异常
	 */
	public static String download(String urlString) {
		InputStream is = null;
		OutputStream os = null;
		try {
			URL url = new URL(urlString);   //构造URL
			URLConnection con = url.openConnection();//打开连接
			is = con.getInputStream(); // 输入流
			byte[] bs = new byte[1024];// 1K的数据缓冲
			int len; // 读取到的数据长度
			String[] sp = urlString.split("/");// 输出的文件流
			os = new FileOutputStream(File_Temp_Path + sp[sp.length - 1]);
			while ((len = is.read(bs)) != -1) {// 开始读取
				os.write(bs, 0, len);
			}
			// 完毕，关闭所有链接
			return File_Temp_Path + sp[sp.length - 1];
		} catch (Exception e) {
			e.printStackTrace();
			LogKit.error("图片抓取错误：" + urlString);
			return null;
		} finally {
			try {
				if (os != null) {
					os.close();
				}
				if (is != null) {
					is.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

	}
}
